﻿using System.Collections.Generic;
using Microsoft.Windows.Design.PropertyEditing;

namespace DenisVuyka.Controls.PropertyGrid.Data
{
  public class PropertyEntryComparer : IComparer<PropertyEntry>
  {
    /// <summary>
    /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
    /// </summary>
    /// <param name="x">The first object to compare.</param>
    /// <param name="y">The second object to compare.</param>
    /// <returns>
    /// Value
    /// Condition
    /// Less than zero
    /// <paramref name="x"/> is less than <paramref name="y"/>.
    /// Zero
    /// <paramref name="x"/> equals <paramref name="y"/>.
    /// Greater than zero
    /// <paramref name="x"/> is greater than <paramref name="y"/>.
    /// </returns>
    public virtual int Compare(PropertyEntry x, PropertyEntry y)
    {
      PropertyItem left = (PropertyItem)x;
      PropertyItem right = (PropertyItem)y;

      //PropertyOrder leftOrder = PropertyOrder.Default;
      //if (left.Attributes != null)
      //{
      //  PropertyOrderAttribute attribute = left.Attributes[typeof(PropertyOrderAttribute)] as PropertyOrderAttribute;
      //  if (attribute != null)
      //    leftOrder = attribute.Order;
      //}

      //PropertyOrder rightOrder = PropertyOrder.Default;
      //if (right.Attributes != null)
      //{
      //  PropertyOrderAttribute attribute = right.Attributes[typeof(PropertyOrderAttribute)] as PropertyOrderAttribute;
      //  if (attribute != null)
      //    rightOrder = attribute.Order;
      //}

      int leftOrder = 0;
      if (left.Attributes != null)
      {
        Metadata.PropertyOrderAttribute attribute = left.GetAttribute<Metadata.PropertyOrderAttribute>();
        if (attribute != null)
          leftOrder = attribute.Order;
      }

      int rightOrder = 0;
      if (right.Attributes != null)
      {
        Metadata.PropertyOrderAttribute attribute = right.GetAttribute<Metadata.PropertyOrderAttribute>();
        if (attribute != null)
          rightOrder = attribute.Order;
      }

      int num = (leftOrder == rightOrder) ? 0 : leftOrder.CompareTo(rightOrder);
      if (num != 0) return num;
      return x.PropertyName.CompareTo(y.PropertyName);
    }    
  }
}
